package caixinyu.experiment12.service;

import caixinyu.experiment12.model.Student;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class StudentService {
    private List<Student> students = new ArrayList<>();
    private long idCounter = 1;

    public StudentService() {
        // 初始化一些学生数据
        students.add(new Student(idCounter++, "John", "Doe", "john.doe@example.com", 20));
        students.add(new Student(idCounter++, "Jane", "Doe", "jane.doe@example.com", 22));
    }

    public List<Student> findAllStudents() {
        return students;
    }

    public Optional<Student> findStudentById(Long id) {
        return students.stream().filter(student -> student.getId().equals(id)).findFirst();
    }

    public Student createStudent(Student student) {
        student.setId(idCounter++);
        students.add(student);
        return student;
    }

    public Optional<Student> updateStudent(Long id, Student student) {
        Optional<Student> existingStudent = findStudentById(id);
        existingStudent.ifPresent(s -> {
            s.setFirstName(student.getFirstName());
            s.setLastName(student.getLastName());
            s.setEmail(student.getEmail());
            s.setAge(student.getAge());
        });
        return existingStudent;
    }

    public boolean deleteStudent(Long id) {
        return students.removeIf(student -> student.getId().equals(id));
    }
}
